package com.huajiao.management_system.config;

import com.huajiao.management_system.service.proveService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author: yuan
 * @Date: 2020/5/21 11:02
 * @Version 1.0
 */
@Component
public class DeleteImgTask implements ServletContextListener {
    @Resource
    proveService proveService;
    private Timer timer = null;
    /**
     * * Notification that the web application initialization process is starting.
     * All ServletContextListeners are notified of context initialization before
     * any filter or servlet in the web application is initialized.
     *
     * @param sce Information about the ServletContext that was initialized
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        timer = new Timer(true);
        sce.getServletContext().log("定时器已启动");
        //延迟60秒，定时1周
        timer.schedule(new OneTask(),60000,604800000);
    }

    /**
     * * Notification that the servlet context is about to be shut down. All
     * servlets and filters have been destroy()ed before any
     * ServletContextListeners are notified of context destruction.
     *
     * @param sce Information about the ServletContext that was destroyed
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if (timer != null) {
            timer.cancel();
            sce.getServletContext().log("定时器销毁");
        }
    }
    class OneTask extends TimerTask {

        /**
         * The action to be performed by this timer task.
         */
        @Override
        public void run() {
            List<String> deleteUrl = proveService.getDeleteUrl();
            for (String fullFilePath : deleteUrl) {
                File deleteFile = new File(fullFilePath);
                if (deleteFile.exists() && deleteFile.isFile()) {
                    deleteFile.delete();
                }
            }
        }
    }
}
